from django.views import View
# 导入返回响应
from SaaSDevelTool.data_return_response import create_response
# 导入错误信息装饰器
from SaaSDevelTool.data_return_response import error_message_detection
# 导入数据库连接
from SaaSDevelTool.data_mysql_data import db
# 获取token
from SaaSDevelTool.data_user_func import user


class SaaSDataTenementApiCreate(View):
    @error_message_detection
    def post(self, request):
        # 获取公司编号
        company_id = request.POST.get('company_id')
        # 获取支付名称
        api_name = request.POST.get('api_name')
        # 获取支付方式
        payment_type = request.POST.get('payment_type')  # 0:微信支付 1：支付宝支付
        # 获取微信支付商户号
        wechat_payment_merchant_num = request.POST.get('wechat_payment_merchant_num')
        # 获取微信商户证书序列号
        wechat_merchant_ccie_num = request.POST.get('wechat_merchant_ccie_num')
        # 获取微信api v3密匙
        wechat_api_v3_key = request.POST.get('wechat_api_v3_key')
        # 获取微信appid
        wechat_app_id = request.POST.get('wechat_app_id')
        # 获取apiclient_cert.p12证书地址
        apiclient_cert_p12_url = request.POST.get('apiclient_cert_p12_url')
        # 获取apiclient_cert.pem证书地址
        apiclient_cert_pem_url = request.POST.get('apiclient_cert_pem_url')
        # 获取apiclient_key.pem证书地址
        apiclient_key_pem_url = request.POST.get('apiclient_key_pem_url')
        # 获取固定成本
        firm_this = request.POST.get('firm_this')
        # 获取出售成本
        sell_this = request.POST.get('sell_this')
        # 获取注释
        api_remark = request.POST.get('api_remark')
        # 判断以上所有填写是否为空
        if not all([company_id, api_name, payment_type, wechat_payment_merchant_num, wechat_merchant_ccie_num,
                    wechat_api_v3_key, wechat_app_id, apiclient_cert_p12_url, apiclient_cert_pem_url,
                    apiclient_key_pem_url, firm_this, sell_this, api_remark]):
            return create_response(code=400,
                                   msg='添加失败:支付名称,支付方式,支付商户号,商户证书序列号,商户证书序列号,apiv3密匙,appid,apiclient_cert.p12证书地址,apiclient_cert.pem证书地址,apiclient_key.pem证书地址,固定成本,出售成本，注释不能为空'
                                   )
        # 判断公司是否存在sql
        judge_company_exist_sql = """
                SELECT
                        tenement_name
                FROM
                        db_saas_center.sum_up_tenement_table
                WHERE
                        tenement_id = {}
            """.format(company_id)
        # 执行判断公司是否存在sql
        tenement_name = db.findOne(judge_company_exist_sql)
        # 判断公司是否存在
        if not tenement_name['tenement_name']:
            return create_response(code=400, msg='添加失败：公司不存在', data='')
        # 判断支付名称是否重复sql
        judge_api_name_exist_sql = """
                SELECT
                    count(0)
                FROM
                    db_tenement_{}.base_info_payment_api_settings
                WHERE
                    api_name = '{}'
        """.format(company_id,api_name)
        # 执行判断支付名称是否重复sql
        is_exist_api_name = db.findOne(judge_api_name_exist_sql)
        if is_exist_api_name['count(0)'] != 0:
            return create_response(code=400,msg='添加失败：支付名称已存在，不可重复添加')
        # 判断固定成本和出售成本是否为小数
        try:
            float(firm_this)
            float(sell_this)
        except Exception as err:
            return create_response(code=400, msg='添加失败：固定成本和出售成本应为数值小数')
        # 判断固定成本和出售成本是否大于1
        if float(firm_this) + float(sell_this) >= 1:
            return create_response(code=400, msg='添加失败：固定成本和出售成本相加不能大于1')
        # 添加租户支付api sql
        create_tenement_api_sql = """
            INSERT INTO
                db_tenement_{}.base_info_payment_api_settings
                        (api_name,
                        payment_type,
                        value1,
                        value2,
                        value3,
                        value4,
                        value5,
                        value6,
                        value7,
                        firm_this,
                        sell_this,
                        api_remark
                        )
            VALUES ('{}','{}','{}','{}','{}','{}','{}','{}','{}',{},{},'{}')
        """.format(company_id, api_name, payment_type, wechat_payment_merchant_num, wechat_merchant_ccie_num,
                   wechat_api_v3_key, wechat_app_id, apiclient_cert_p12_url, apiclient_cert_pem_url,
                   apiclient_key_pem_url, firm_this, sell_this, api_remark)
        # 执行添加租户支付api sql
        db.update(create_tenement_api_sql)
        # 获取token
        token = user.get_user(request)
        # 解析token获取用户id
        user_id = token['user_id']
        # 获取公司名称
        tenement_name = tenement_name['tenement_name']
        # 拼接日志信息
        log_message = f'企业编号:{company_id}-支付api管理：新增了{tenement_name}的api管理，名称为{api_name}'
        # 添加日志sql
        create_log_sql = """
            INSERT INTO
                db_center_rbac.base_info_log_table
                    (
                    user_id,
                    create_time,
                    log_message
                    )
            VALUES
                ({},NOW(),'{}')
        """.format(user_id,log_message)
        # 执行sql
        db.update(create_log_sql)
        return create_response(code=200,msg='添加成功')
